package cn.wenzy.aurora.framework.support.validation.annotation.impl;

import cn.hutool.extra.spring.SpringUtil;
import cn.wenzy.aurora.framework.support.i18n.I18nSupport;
import cn.wenzy.aurora.framework.support.validation.annotation.RuleValidation;
import cn.wenzy.aurora.framework.support.validation.bean.ValidationMessage;
import cn.wenzy.aurora.framework.support.validation.ValidationSupport;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

public class RuleValidationImpl implements ConstraintValidator<RuleValidation, String> {
    private String ruleCode;
    private String message;
    private I18nSupport i18n;
    private ValidationSupport validation;

    @Override
    public void initialize(RuleValidation annotation) {
        ruleCode = annotation.ruleCode();
        message = annotation.message();
        i18n = SpringUtil.getBean(I18nSupport.class);
        validation = SpringUtil.getBean(ValidationSupport.class);
    }

    @Override
    public boolean isValid(String str, ConstraintValidatorContext context) {
        ValidationMessage validationMessage = validation.validateRule(ruleCode, str);
        if (!validationMessage.isValidate()) {
            message = i18n.getMessage(message, validationMessage.message());
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
        }
        return validationMessage.isValidate();
    }
}
